package com.abu.edums.controller.front;

import com.abu.edums.mapper.CourseMapper;
import com.abu.edums.service.impl.CourseFrontService;
import com.abu.exceptionhandler.EduException;
import com.abu.vo.CourseQueryVo;
import com.abu.utils.Resp;
import com.abu.vo.CourseWebVo;
import com.alibaba.fastjson.JSON;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/eduservice/coursefront")
public class CourseFrontController {

    @Autowired
    private CourseFrontService frontService;


    private static final String PREFIX = "COURSE:PREFIX:";
    @Autowired
    private CourseMapper courseMapper;


    @PostMapping("getFrontCourseList/{page}/{limit}")
    public Resp getFrontCourseList(
            @RequestBody(required = false) CourseQueryVo queryVo,
            @PathVariable("page") Long page,
            @PathVariable("limit") Long limit
    ) {
        Map<String, Object> map = this.frontService.queryFrontList(queryVo, page, limit);
        if (CollectionUtils.isEmpty(map)) {
            throw new EduException(20001, "查询数据为空");
        }
        return Resp.ok().data(map);
    }

    /**
     * 读的多写的少，加缓存。倘若写的多，那么一边要写数据库，一边还要写缓存，双写使得性能降低
     * <p>
     * 查询课程信息=》获取课程信息和 相应的章节和小节信息
     *
     * @param courseId
     * @return
     */
    @GetMapping("getFrontCourseInfo/{courseId}")
    public Resp getFrontCourseInfo(@PathVariable("courseId") String courseId, HttpServletRequest request) {
/*//        1.查询缓存中有没有数据
        String courseWebJson = this.redisTemplate.opsForValue().get(PREFIX + courseId);
//        2.有数据返回
        if (!StringUtils.isEmpty(courseWebJson)) {
            HashMap map = JSON.parseObject(courseWebJson, HashMap.class);
            return Resp.ok().data(map);
        }
//        3.无数据则加分布式锁
        RLock lock = redissonClient.getLock("LOCK:" + courseId);
        lock.lock();
//        4.再次查询缓存
        String courseWebJson02 = this.redisTemplate.opsForValue().get(PREFIX + courseId);
//        5.有数据则返回(别忘了释放锁)
        if (!StringUtils.isEmpty(courseWebJson02)) {
            HashMap map = JSON.parseObject(courseWebJson02, HashMap.class);
//            5.1释放锁
            lock.unlock();
            return Resp.ok().data(map);
        }*/
//        6.无数据则查询数据库
        HashMap<String, Object> map = this.frontService.queryCourseWeb(courseId, request);
//        7.将数据放入缓存中(返回数据之前要记得释放锁)
//        String mapJson = JSON.toJSONString(map);
//        this.redisTemplate.opsForValue().set(PREFIX + courseId, mapJson, 60 + new Random().nextInt(10) + 1, TimeUnit.MINUTES);
//          7.1释放锁
//        lock.unlock();
        return Resp.ok().data(map);
    }

    @GetMapping("getFrontCourseDetails/{courseId}")
    public CourseWebVo queryCourseWebVo(@PathVariable("courseId") String courseId) {
        return this.courseMapper.queryCourseWebInfo(courseId);
    }
}
